package com.summer.controller.userManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.config.YouxinSMSConfig;
import com.summer.controller.BaseController;
import com.summer.entity.*;
import com.summer.mapper.PlatformRoleMapper;
import com.summer.service.IPlateformRoleService;
import com.summer.service.IPlateformUserService;
import com.summer.util.*;
import com.summer.variable.Constant;
import com.summer.vo.PlatformUserRoleVo;
import com.summer.vo.PlatformUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserLoginController extends BaseController{

    @Resource
    private IPlateformUserService plateformUserService;

    @Resource
    private YouxinSMSConfig youxinSMSConfig;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private PlatformRoleMapper platformRoleMapper;

    @Resource
    private IPlateformRoleService plateformRoleService;

    /**
     * 发送验证码
     * @return
     */
    @PostMapping(value = "/sendCode")
    public String sendCode(@RequestBody PlatformUser platformUser) {
        String code = "";
        Date now =new Date();
        PlatformUser loginInfo = plateformUserService.findByPhoneNumber(platformUser.getPhoneNumber());
        if (loginInfo==null) {
            return CallBackResult.returnJson(9900,"该用户不存在");
        }
        //检验验证码是否过期
        if (now.compareTo(loginInfo.getLastCodeTime()) < 0) {
            return CallBackResult.returnJson(450,"验证码未过期，请查看短信");
        }else {
            //更新用户信息的验证码和验证码有效期
            code = RandomUtil.getCode();
            loginInfo.setCode(code);
            loginInfo.setLastCodeTime(new Date(now.getTime() + 1800000));
            if (youxinSMSConfig.sendCode(platformUser.getPhoneNumber(),code,Constant.CONTENT_TITLE)) {
                plateformUserService.update(loginInfo);
                return CallBackResult.returnJson(200,"发送消息成功");
            }else {
                return CallBackResult.returnJson(300,"发送消息失败");
            }
        }
    }

    /**
     * 用户登录
     * @param platformUser
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/login")
    public String login(@RequestBody PlatformUser platformUser,HttpServletRequest request) throws Exception {
        Date now = new Date();
        PlatformUser loginInfo = plateformUserService.findByPhoneNumber(platformUser.getPhoneNumber());
        if (StringUtils.isEmpty(loginInfo.getPhoneNumber())) {
            return CallBackResult.returnJson(9909,"手机号为空或不存在");
        }
        //登录ip
        String ipAddr = IPUtils.getIpAddr(request);
         //判断用户名和密码、验证码
         String token = plateformUserService.userLogin(platformUser);
         loginInfo.setLastLoginTime(now);
         loginInfo.setIpAddress(ipAddr);
         plateformUserService.update(loginInfo);
         //将用户信息放到缓存中
         redisUtil.set(Constant.TOKEN+token, JSON.toJSONString(loginInfo),1800);
         return token;
    }

    /**
     * 添加用户
     * @param jsonData
     */
    @PostMapping("/addUser")
    public String addUser(@RequestBody String jsonData,HttpServletRequest request) {
        //获取当前用户信息
        PlatformUser platformUser=redisPlatformUser(request);
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("UserLoginController addUser params=" + params.toString());
        Date now = new Date();
        String phoneNumber= (String) params.get("phoneNumber");
        String roleName= (String) params.get("roleName");
        String userName= (String) params.get("userName");
        PlatformUser user = plateformUserService.findByPhoneNumber(phoneNumber);
        if (user!=null){
            return CallBackResult.returnJson("该电话已存在,请重新输入");
        }

        //得到角色id
        PlatformRole platformRole = platformRoleMapper.selectByRoleName(roleName);

        PlatformUser saveUser=new PlatformUser();
        saveUser.setUserName(userName);
        saveUser.setCreateTime(now);
        saveUser.setRoleId(platformRole.getId());
        saveUser.setSalt(RandomUtil.getRandomSalt());
        saveUser.setPassword(MD5Util.md5(Constant.DEFAULT_PASSWORD+saveUser.getSalt()));
        saveUser.setPhoneNumber(phoneNumber);
        saveUser.setUserSuperId(platformUser.getId());
        try {
            plateformUserService.save(saveUser);
            return CallBackResult.returnJson(CallBackResult.CREATED,CallBackResult.MSG_CREATED);
        }catch (Exception e){
            e.printStackTrace();
            return CallBackResult.returnJson(CallBackResult.INVALID_REQUEST,CallBackResult.MSG_INVALID_REQUEST);
        }

    }

    /**
     * 账户管理列表
     * @param jsonData
     * @return
     */
    @PostMapping("/queryUser")
    public String queryUser(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("UserLoginController queryUser params=" + params.toString());
        PageHelper.startPage(params);
        PageInfo<PlatformUserVo> pageInfo = plateformUserService.findParams(params);
        if (pageInfo==null){
            return CallBackResult.returnJson("列表信息为空或不存在");
        }
        return CallBackResult.returnJson(pageInfo);
    }

    /**
     * 角色管理列表
     * @param jsonData
     * @return
     */
    @PostMapping("/queryUserRole")
    public String queryUserRole(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("【角色管理列表】角色管理列表 params={}",params.toString());
        List<PlatformUserRoleVo> result = plateformRoleService.findParams(params);
        if (result==null){
            return CallBackResult.returnJson("角色列表信息为空或不存在");
        }
        return CallBackResult.returnJson(result);
    }
    /**
     * 删除用户
     * @param jsonData
     * @return
     */
    @PostMapping("/deleteByStatus")
    public String deleteByStatus(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("UserLoginController deleteByStatus params=" + params.toString());
        try {
            plateformUserService.deleteByStatus(params);
            return CallBackResult.returnJson(CallBackResult.NO_CONTENT_SUCCESS,CallBackResult.MSG_NO_CONTENT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return CallBackResult.returnJson(CallBackResult.INVALID_REQUEST_FAIL,CallBackResult.MSG_INVALID_REQUEST_FAIL);
        }
    }

    /**
     * 修改用户角色
     * @param jsonData
     */
    @PostMapping("/updateByRole")
    public String updateByRole(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("UserLoginController updateByRole params=" + params.toString());
        try {
            plateformUserService.updateByRole(params);
            return CallBackResult.returnJson(CallBackResult.CREATED,CallBackResult.MSG_CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return CallBackResult.returnJson(CallBackResult.INVALID_REQUEST,CallBackResult.MSG_INVALID_REQUEST);
        }
    }
}
